import java.sql.*;

public class UserDao {

    private static final String DB_URL = "jdbc:mysql://localhost:3306/jdbc?serverTimezone=GMT%2B8&useSSL=false";
    private static final String DB_USERNAME = "root";
    private static final String DB_PASSWORD = "123456";

    public User getUserByUsername(String username) {
        User user = null;

        try (Connection con = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
             PreparedStatement ps = con.prepareStatement("SELECT * FROM users_tbl WHERE username=?")) {

            ps.setString(1, username);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    String password = rs.getString("password");
                    user = new User(username, password);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return user;
    }

    public void registerUser(User user) {
        RegisterDao registerDao = new RegisterDao();
        registerDao.registerUser(user);
    }

    public boolean isUsernameExists(String username) {
        boolean exists = false;

        try (Connection con = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
             PreparedStatement ps = con.prepareStatement("SELECT * FROM users_tbl WHERE username=?")) {

            ps.setString(1, username);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    exists = true;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return exists;
    }

}
